package com.roger.ndtplayer.commom.core

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import com.roger.ndtplayer.commom.ext.putExtras

/**
 * ActivityHelper
 */
object ActivityHelper {

    private lateinit var applicationContext: Context

    fun init(application: Application) {
        applicationContext = application.applicationContext
        activities.clear()
        application.registerActivityLifecycleCallbacks(ActivityLifecycleCallbacksAdapter(
            onActivityCreated = { activity, _ ->
                activities.add(activity)
            },
            onActivityDestroyed = { activity ->
                activities.remove(activity)
            }
        ))
    }

    private val activities = mutableListOf<Activity>()


    /**
     * 使用方法
     * ActivityHelper.startActivity(
    DetailActivity::class.java, mapOf(DetailActivity.PARAM_ARTICLE to article)
    )
     */
    @JvmOverloads
    fun startActivity(
        clazz: Class<out Activity>,
        params: Map<String, Any> = emptyMap(),
    ) {
        val currentActivity = activities[activities.lastIndex]
        val intent = Intent(currentActivity, clazz)
        params.forEach {
            intent.putExtras(it.key to it.value)
        }
        currentActivity.startActivity(intent)
    }

    //    初始化intent
    fun createIntent(
        clazz: Class<out Activity>,
        params: Map<String, Any> = emptyMap(),
    ): Intent {
        val currentActivity = activities[activities.lastIndex]
        val intent = Intent(currentActivity, clazz)
        params.forEach {
            intent.putExtras(it.key to it.value)
        }
        return intent
    }

    /**
     * finish指定的一个或多个Activity
     */
    fun finish(vararg clazz: Class<out Activity>) {
        activities.forEach { ac ->
            if (clazz.contains(ac::class.java)) {
                ac.finish()
            }
        }
    }

    /**
     * 关闭所有Activity
     */
    fun closeAllActivity() {
        activities.forEach { ac ->
            ac.finish()
        }
    }

}